/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.knowledge.group.controller;

import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DBSort;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.knowledge.doc.domain.DocGroup;
import com.wallellen.knowledge.doc.domain.ex.DocEntire;
import com.wallellen.knowledge.doc.exception.CanNoWriteException;
import com.wallellen.knowledge.doc.server.DocManagerInter;
import com.wallellen.knowledge.doc.server.DocgroupManagerInter;
import com.wallellen.knowledge.doc.server.FileManagerInter;
import com.wallellen.util.web.FormatUnits;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 文件
 *
 * @author <a href="mailto:wallellen@hotmail.com">WALLE</a>
 */
@RequestMapping("/group")
@Controller
public class GroupController extends WebUtils {
    @Resource
    private DocgroupManagerInter docgroupManagerImpl;
    @Resource
    private FileManagerInter fileManagerImpl;
    @Resource
    private DocManagerInter docManagerImpl;

    /**
     * 查询我的小组文档
     *
     * @return
     */
    @RequestMapping("/searchGroupDoc")
    @ResponseBody
    public Map<String, Object> searchGroupDoc(String searchDocKey, DataQuery query, HttpSession session) {
        try {
            if (searchDocKey != null && searchDocKey.trim().length() > 0) {
                query.addRule(new DBRule("a.TITLE", searchDocKey, "like"));
            }
            DataResult result = docgroupManagerImpl.createUserGroupDocQuery(query, getCurrentUser(session).getId())
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                if (node.get("GROUPIMG") != null) {
                    node.put("GROUPIMG", fileManagerImpl.getFileURL(node.get("GROUPIMG").toString()));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 初始化小组首页数据
     *
     * @return
     */
    @RequestMapping("/group")
    public ModelAndView loadGroupHome(String gourpid) {
        // 获取小组首页
        DocGroup group = docgroupManagerImpl.getDocgroupEntity(gourpid);
        DocEntire doc = docManagerImpl.getDoc(group.getHomedocid());
        return ViewMode.getInstance().returnModelAndView("");
    }

    /**
     * 提交小组首页修改
     *
     * @return
     */
    @RequestMapping("/editCommit")
    public ModelAndView editGroupHomeCommit(DocEntire doc, String editNote, String text, HttpSession session) {
        doc = docManagerImpl.getDoc(doc.getDoc().getId());
        doc.getTexts().setText1(text);
        try {
            docManagerImpl.editDocByUser(doc, editNote, getCurrentUser(session));
        } catch (CanNoWriteException e) {
            return ViewMode.getInstance().setError(e + e.getMessage()).returnModelAndView("");
        }
        return ViewMode.getInstance().returnModelAndView("");
    }

    /**
     * 编辑小组首页
     *
     * @return
     */
    @RequestMapping("/edit")
    public ModelAndView editGroupHome(String groupid) {
        // 获取小组首页
        DocGroup group = docgroupManagerImpl.getDocgroupEntity(groupid);
        DocEntire doc = docManagerImpl.getDoc(group.getHomedocid());
        return ViewMode.getInstance().putAttr("group", group).putAttr("doc", doc).returnModelAndView("");
    }

    /**
     * 首页我的小组动态
     *
     * @return
     */
    @RequestMapping("/myGroupDoc")
    @ResponseBody
    public Map<String, Object> myGroupDoc(HttpSession session) {
        DataResult result = null;
        try {
            result = docgroupManagerImpl.createUserGroupDocQuery(new DataQuery(), getCurrentUser(session).getId())
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                if (node.get("GROUPIMG") != null) {
                    node.put("GROUPIMG", fileManagerImpl.getFileURL(node.get("GROUPIMG").toString()));
                }
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
    }

    /**
     * 加载用户小组动态
     *
     * @return
     */
    @RequestMapping("/userGroupDoc")
    @ResponseBody
    public Map<String, Object> userGroupDoc(HttpServletRequest request, DataQuery query, String userId) {
        DataResult result = null;
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            query.setPagesize(3);
            result = docgroupManagerImpl.createDocgroupQueryJoinUser(query)
                    .addRule(new DBRule("a.PSTATE", "1", "=")).addRule(new DBRule("b.PSTATE", "1", "="))
                    .addRule(new DBRule("b.USERID", userId, "=")).addSort(new DBSort("SHOWSORT,a.CTIME", "ASC"))
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                if (node.get("GROUPIMG") != null) {
                    node.put("GROUPIMG", fileManagerImpl.getFileURL(node.get("GROUPIMG").toString()));
                }
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result).returnObjMode();
    }

    /**
     * 首页公共小组
     *
     * @return
     */
    @RequestMapping("/pubGroup")
    @ResponseBody
    public Map<String, Object> loadHomePubGroup(HttpServletRequest request, HttpSession session) {
        DataResult result = null;
        try {
            DataQuery query = EasyUiUtils.formatGridQuery(request, new DataQuery());

            query.setPagesize(4);
            if (getCurrentUser(session) != null) {
                query = docgroupManagerImpl.createFarmDocgroupQueryNuContainUser(query,
                        getCurrentUser(session).getId());
                result = query.addRule(new DBRule("a.PSTATE", "1", "=")).search();
            } else {
                query = docgroupManagerImpl.createDocgroupQuery(query);
                result = query.addRule(new DBRule("PSTATE", "1", "=")).search();

            }
            query.addSort(new DBSort("USERNUM", "desc"));
            for (Map<String, Object> node : result.getResultList()) {
                if (node.get("GROUPIMG") != null) {
                    node.put("GROUPIMG", fileManagerImpl.getFileURL(node.get("GROUPIMG").toString()));
                }
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result.getResultList()).returnObjMode();
    }

    /**
     * 加载小组的最新文档
     *
     * @return
     */
    @RequestMapping("/userGroupDocNew")
    @ResponseBody
    public Map<String, Object> loadGroupNewDoc(String groupid, HttpSession session) {
        DataResult result = null;
        try {
            result = docgroupManagerImpl.getGroupNewDocQuery(new DataQuery(), groupid, getCurrentUser(session))
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                node.put("PUBTIME", FormatUnits.getFormateTime(node.get("PUBTIME").toString(), true));
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result.getResultList()).returnObjMode();
    }

    /**
     * 加载小组的优质文档
     *
     * @return
     */
    @RequestMapping("/userGroupDocGood")
    @ResponseBody
    public Map<String, Object> loadGroupGoodDoc(String groupid, HttpSession session) {
        DataResult result = null;
        try {
            result = docgroupManagerImpl.getGroupGoodDocQuery(new DataQuery(), groupid, getCurrentUser(session))
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                node.put("PUBTIME", FormatUnits.getFormateTime(node.get("PUBTIME").toString(), true));
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result.getResultList()).returnObjMode();
    }

    /**
     * 加载小组的待改善文档
     *
     * @return
     */
    @RequestMapping("/userGroupDocBad")
    @ResponseBody
    public Map<String, Object> loadGroupBadDoc(String groupid, HttpSession session) {
        DataResult result = null;
        try {
            result = docgroupManagerImpl.getGroupBadDocQuery(new DataQuery(), groupid, getCurrentUser(session))
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                node.put("PUBTIME", FormatUnits.getFormateTime(node.get("PUBTIME").toString(), true));
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result.getResultList()).returnObjMode();
    }

    /**
     * 加载小组的最热文档
     *
     * @return
     */
    @RequestMapping("/userGroupDocHot")
    @ResponseBody
    public Map<String, Object> loadGroupHotDoc(String groupid, HttpSession session) {
        DataResult result = null;
        try {
            result = docgroupManagerImpl.getGroupHotDocQuery(new DataQuery(), groupid, getCurrentUser(session))
                    .search();
            for (Map<String, Object> node : result.getResultList()) {
                node.put("PUBTIME", FormatUnits.getFormateTime(node.get("PUBTIME").toString(), true));
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result.getResultList()).returnObjMode();
    }

    /**
     * 小组首页显示
     *
     * @return
     */
    @RequestMapping("/home")
    public ModelAndView groupHomeShow(HttpSession session, String gourpid) {
        try {
            docgroupManagerImpl.setGroupHomeShow(gourpid, getCurrentUser(session).getId());
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e + e.getMessage()).returnModelAndView("");
        }
        return ViewMode.getInstance().returnModelAndView("");
    }

    /**
     * 小组首页隐藏
     *
     * @return
     */
    @RequestMapping("/hideHome")
    @ResponseBody
    public Map<String, Object> hideHome(String groupId, HttpSession session) {
        try {
            docgroupManagerImpl.setGroupHomeHide(groupId, getCurrentUser(session).getId());
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 小组显示排序上移
     *
     * @return
     */
    @RequestMapping("/sortUp")
    @ResponseBody
    public Map<String, Object> groupSortUp(String groupId, HttpSession session) {
        try {
            docgroupManagerImpl.setGroupSortUp(groupId, getCurrentUser(session).getId());
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 设置为小组管理员
     *
     * @return
     */
    @RequestMapping("/setAdmin")
    @ResponseBody
    public Map<String, Object> groupSetAdmin(String groupUserId, HttpSession session) {
        try {
            docgroupManagerImpl.setAdminForGroup(groupUserId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 设置小组编辑权限
     *
     * @return
     */
    @RequestMapping("/setEditor")
    @ResponseBody
    public Map<String, Object> groupSetEditor(String groupUserId, HttpSession session) {
        try {
            docgroupManagerImpl.setEditorForGroup(groupUserId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 去除小组编辑权限
     *
     * @return
     */

    @RequestMapping("/wipeEditor")
    @ResponseBody
    public Map<String, Object> groupWipeEditor(String groupUserId, HttpSession session) {
        try {
            docgroupManagerImpl.wipeEditorForGroup(groupUserId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 同意加入申请
     *
     * @return
     */
    @RequestMapping("/agreeApply")
    @ResponseBody
    public Map<String, Object> groupAgreeApply(String groupUserId, HttpSession session) {
        try {
            docgroupManagerImpl.agreeJoinApply(groupUserId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 拒绝加入申请
     *
     * @return
     */
    @RequestMapping("/refuseApply")
    @ResponseBody
    public Map<String, Object> groupRefuseApply(String groupUserId, HttpSession session) {
        try {
            docgroupManagerImpl.refuseJoinApply(groupUserId, getCurrentUser(session));
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().returnObjMode();
    }

    /**
     * 加载我的小组
     *
     * @return
     */
    @RequestMapping("/leave")
    @ResponseBody
    public Map<String, Object> loadGroups(HttpServletRequest request, HttpSession session) {
        DataQuery query;
        DataResult result;
        try {
            query = EasyUiUtils.formatGridQuery(request, new DataQuery());
            query.setPagesize(3);
            result = docgroupManagerImpl.createDocgroupQueryJoinUser(query)
                    .addRule(new DBRule("a.PSTATE", "1", "=")).addRule(new DBRule("b.PSTATE", "1", "="))
                    .addRule(new DBRule("b.USERID", getCurrentUser(session).getId(), "="))
                    .addSort(new DBSort("SHOWSORT,a.CTIME", "ASC")).search();
            for (Map<String, Object> node : result.getResultList()) {
                if (node.get("GROUPIMG") != null) {
                    node.put("GROUPIMG", fileManagerImpl.getFileURL(node.get("GROUPIMG").toString()));
                }
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e + e.getMessage()).returnObjMode();
        }
        return ViewMode.getInstance().putAttr("result", result).returnObjMode();
    }


}
